//
//  IGCList4SearchVC.m
//  jingdongfang
//
//  Created by BOE on 2017/9/14.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "IGCList4SearchVC.h"
#import "IGCommunityModel.h"
#import "IGCommunityListApi.h"
#import "IGCommunityListTableViewCell.h"
#import "IGEmptyView.h"

@interface IGCList4SearchVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *communityMuArr;

@property (nonatomic, strong) NSIndexPath *selectIndexPath;
    
@property (nonatomic, assign) IGCommunityListType listType;
@property (nonatomic, strong) IGCommunityListApi *listApi;
@property (nonatomic, copy) NSString *lastTimeDate;
@property (nonatomic, assign) NSInteger page;
    
@end

@implementation IGCList4SearchVC
    
- (instancetype)initWithListType:(IGCommunityListType)listType {
    self = [super init];
    if (self) {
        self.lastTimeDate = @"0";
        self.page = 1;
        self.listApi = [[IGCommunityListApi alloc] initWithType:listType lastTimeDate:self.lastTimeDate page:_page];
        _listType = listType;
    }
    return self;
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"选择圈子";
    self.title = NSLocalizedString(@"Select Group", nil);
    AdjustsScrollViewInsetNever(self, self.tableView);
    
    self.view.backgroundColor = [UIColor mainBackgroundColor];
//    [self ig_setupRightButtonItemWithTitle:@"确定" image:nil highLightedImage:nil];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Confirm", nil) image:nil highLightedImage:nil];

    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(NavigationMagin);
    }];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setHeaderWithRefreshingBlock:^{
        weakSelf.lastTimeDate = @"0";
        weakSelf.page = 1;
        weakSelf.listApi.lastTimeDate = weakSelf.lastTimeDate;
        weakSelf.listApi.page = weakSelf.page;
        
        [weakSelf requestData];
    }];
    [self requestData];
}
    
- (void)requestData {
    __weak typeof(self) weakSelf = self;
    [self.listApi startWithDecodeClass:[IGCommunityListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [weakSelf.tableView ig_endHeaderRefreshing];
        [weakSelf.tableView ig_endFooterRefreshing];
        
        if (responseObject) {
            IGCommunityListResp *resp = responseObject;
            IGCommunityListModel *model = resp.data;
            
            NSArray *tmpCommunityArr = model.circles;
            if (tmpCommunityArr && tmpCommunityArr.count > 0) {
                [weakSelf setupFooter];
            } else {
                [weakSelf.tableView ig_endFooterRefreshingWithNoMoreData];
            }
            
            if ([weakSelf.lastTimeDate isEqualToString:@"0"]) {
                weakSelf.communityMuArr = [NSMutableArray arrayWithArray:tmpCommunityArr];
            } else {
                [weakSelf.communityMuArr addObjectsFromArray:tmpCommunityArr];
            }
            weakSelf.lastTimeDate = model.lastTimeDate;
            
            if (self.selectModel) {
                for (int i = 0; i< weakSelf.communityMuArr.count; i++) {
                    IGCommunityModel *model = weakSelf.communityMuArr[i];
                    if ([model.cid isEqualToString:weakSelf.selectModel.cid]) {
                        model.isSelected = YES;
                        weakSelf.selectModel = model;
                        weakSelf.selectIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                        break;
                    }
                }
            }
            
            [weakSelf.tableView reloadData];
        } else {
            
        }
    }];
}
    
- (void)setupFooter {
    __weak typeof(self) weakSelf = self;
    [self.tableView ig_setFooterWithRefreshingBlock:^{
        weakSelf.page++;
        weakSelf.listApi.page = weakSelf.page;
        weakSelf.listApi.lastTimeDate = weakSelf.lastTimeDate;
        [weakSelf requestData];
    }];
}
    
- (void)ig_rightButtonPressed:(id)sender {
    if (self.itemDidClick) {
        self.itemDidClick(self.selectModel);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
    
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        if (@available(iOS 11.0, *)) {
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }

        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, -100, 0, 0);
    }
    return _tableView;
}
    
#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.communityMuArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IGCommunityListTableViewCell *cell = [IGCommunityListTableViewCell cellWithTableView:tableView listType:self.listType];
    
    IGCommunityModel *model = [self.communityMuArr objectAtIndex:indexPath.row];
    cell.itemModel = model;
    
    return cell;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90.f;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.f;
}
    
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIButton *noSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [noSelectBtn setTitle:@"不关联圈子" forState:UIControlStateNormal];
    [noSelectBtn setTitle:NSLocalizedString(@"No Group Associated", nil) forState:UIControlStateNormal];
    [noSelectBtn setTitleColor:[UIColor c4Color] forState:UIControlStateNormal];
    [noSelectBtn setFrame:CGRectMake(0, 0, KSCREENWIDTH, 50.f)];
    
    UIImageView *rightImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pub_circle_selected"]];
    rightImgView.tag = 100;
    [noSelectBtn addSubview:rightImgView];
    [rightImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kGAP15);
        make.width.height.mas_equalTo(24);
        make.top.mas_equalTo(13);
    }];
    if (self.selectIndexPath) {
        rightImgView.hidden = YES;
    }
    
    __weak typeof(rightImgView) weakRightImgView = rightImgView;
    __weak typeof(self) weakSelf = self;
    [noSelectBtn setTapActionWithBlock:^{
        if (weakSelf.selectIndexPath) {
            self.selectModel.isSelected = NO;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[self.selectIndexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        weakRightImgView.hidden = NO;
        self.selectModel = nil;
        self.selectIndexPath = nil;
    }];
    
    return noSelectBtn;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1f;
}
    
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    IGCommunityModel *model = [self.communityMuArr objectAtIndex:indexPath.row];
    model.isSelected = YES;
    if (self.selectIndexPath && self.selectIndexPath != indexPath) {
        self.selectModel.isSelected = NO;
        [tableView reloadRowsAtIndexPaths:@[indexPath, self.selectIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else {
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    
    UIView *view = [self.view viewWithTag:100];
    view.hidden = YES;
    
    self.selectModel = model;
    self.selectIndexPath = indexPath;
}

#pragma mark -Empty
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    IGEmptyView *emptyView = [[IGEmptyView alloc] init];
//    emptyView.title = @"没有找到圈子~";
    emptyView.title = NSLocalizedString(@"No Group Discovered", nil);
    emptyView.requestApi = self.listApi;
    return emptyView;
}

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
    
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
    
@end
